<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\api\BaseApiController;
use app\admin\model\Token;
use app\system\model\LogLogin as Log;
use think\facade\Cookie;
use app\version\model\Version;

class Profile extends BaseApiController
{
    /**
     * 元数据
     * url: http://域名/api/v1/profile/mine
     * doc: http://lutui.net/doc/app/profile-meta.html
     */
    public function mine()
    {
        $none = DOMAIN . '/static/images/none.png';
        $curr = $this->data['version']; // 当前版本
        $last = Version::order('id', 'desc')->limit(1)->find();
        $metas = $this->trigger('AppProfileMeta');
        $new = [];
        if ($metas) {
            foreach ($metas as $meta) {
                foreach ($meta as $item) {
                    $new[] = $item;
                }
            }
        }
        return json([
            'info' => [
                'nickname' => $this->user->nickname,
                'url' => $this->user->avatar ? DOMAIN . $this->user->avatar : $none,
            ],
            'meta' => $new,
            'update' => $last && $last->version != $curr,
            'items' => [],
        ]);
    }

    /**
     * 退出登录
     * url: http://域名/api/v1/profile/logout
     * doc: http://lutui.net/doc/app/profile-logout.html
     */
    public function logout()
    {
        $obj = Token::where('admin_id', UID)->where('platform', 'app')->find();
        if ($obj) {
            $obj->delete();
        }
        Log::add($this->user->nickname, '退出成功', 'App', 'Android');
        return json(['logout' => 'success']);
    }

    /**
     * 修改密码
     * url: http://域名/api/v1/profile/password
     * doc: http://lutui.net/doc/app/profile-password.html
     */
    public function password()
    {
        $password = $this->data['password'];
        if (empty($password)) {
            return json(['error' => '请输入新密码']);
        }
        $this->user->password = password_hash($password, PASSWORD_DEFAULT);
        $this->user->save();
        Log::add('修改密码', [
            'ID' => UID,
            '昵称' => USERNAME,
        ]);
        Cookie::delete('auth');
        return json(['error' => '']);
    }
}
